package com.jier.common.interceptor;

import com.jier.entities.User;
import com.google.gson.Gson;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jie_r on 2016/9/22.
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("currentUser");
//        if (user == null) {
//            toLogin(response);
//            return false;
//        }
        return true;
    }

    public void toLogin(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            Gson gson = new Gson();
            Map<String, String> map = new HashMap<String, String>();
            map.put("api_code", "1");
            map.put("api_message", "请重新登录");
            String writeMessage = gson.toJson(map);
            out.print(writeMessage);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}
